package com.ruoyi.generator.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.druid.DbType;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.extension.jmliu1983.ds.dynamic.DynamicDataSourceHelper;
import com.ruoyi.framework.datasource.DynamicDataSource;

import com.ruoyi.generator.config.GenConfig;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.IGenTableColumnService;
import com.ruoyi.generator.service.IGenTableService;

/**
 * 代码生成 操作处理
 * 
 * @author ruoyi
 */
@RestController
//@RequestMapping("/tool/gen")
@RequestMapping("/code/gen2")
public class GenController2 extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(GenController2.class);

	@Autowired
	private IGenTableService genTableService;

	@Autowired
	private IGenTableColumnService genTableColumnService;

//	@Value(value = "${gen.useDefaultDatasource}")
//	private boolean useDefaultDatasource;

	@Value(value = "${gen.datasource}")
	private String datasource;

	@Autowired
	private DefaultDataSourceCreator creator;

	@Autowired(required = false)
	private DataSource dataSource;

	/**
	 * 
	 * 
	 * 查询代码生成列表
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:list')")
	@GetMapping("/list")
	public TableDataInfo genList(GenTable genTable) {
		Map<String, Object> queryParams = genTable.getParams();

		Boolean dsChanged = changeDs(queryParams);
		startPage();
		List<GenTable> list = genTableService.selectGenTableList(genTable);

		if (dsChanged)
			resetDs();
		return getDataTable(list);
	}

	/**
	 * 查看当前数据库连接列表
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:list')")
	@GetMapping("/dblist")
	public TableDataInfo genDbList(GenTable genTable) {		
		if (dataSource instanceof DynamicDataSource) {
			return getDataTable(DynamicDataSourceHelper.getDynamicDataSources((DynamicDataSource) dataSource));
		} else if (dataSource instanceof DynamicRoutingDataSource) {
			return getDataTable(
					DynamicDataSourceHelper.getDynamicDruidDataSources((DynamicRoutingDataSource) dataSource));
		}
		return null;
	}

	/**
	 * 导入表结构（保存）
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:import')")
//	@Log(title = "代码生成", businessType = BusinessType.IMPORT)
	@PostMapping("/addds")
	public AjaxResult addDatasource(@RequestBody Map<String, String> param) {
		String dsName = param.get("dsName");
		String dbType = param.get("dbType");
		String userName = param.get("userName");
		String password = param.get("password");
		String jdbcUrl = param.get("jdbcUrl");

		if (dataSource instanceof DynamicDataSource) {
			DynamicDataSourceHelper.addDynamicDataSource((DynamicDataSource) dataSource, creator, dsName, userName,
					password, jdbcUrl, dbType);
		} else if (dataSource instanceof DynamicRoutingDataSource) {
			DynamicDataSourceHelper.addDynamicRoutingDataSource((DynamicRoutingDataSource) dataSource, creator, dsName,
					userName, password, jdbcUrl, dbType);
		}
//		Map<String, DataSource> dsList = dynamicRoutingDataSource.getDataSources();
//		System.out.println(dsList.keySet());
		return success();
	}

	/**
	 * 修改代码生成业务
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:query')")
	@GetMapping(value = "/{tableId}")
	public AjaxResult getInfo(@PathVariable Long tableId, @RequestParam String dsname) {

		Boolean dsChanged = changeDs(dsname);
		GenTable table = genTableService.selectGenTableById(tableId);
		List<GenTable> tables = genTableService.selectGenTableAll();
		List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("info", table);
		map.put("rows", list);
		map.put("tables", tables);

		if (dsChanged)
			resetDs();
		return success(map);
	}

	/**
	 * 查询数据库列表
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:list')")
	@GetMapping("/db/list")
	public TableDataInfo dataList(GenTable genTable) {

		Map<String, Object> queryParams = genTable.getParams();
		List<GenTable> list =null;
		Boolean dsChanged = changeDs(queryParams);
		try {
			startPage();
			list = genTableService.selectDbTableList(genTable);
		}finally{			
			if (dsChanged)
				resetDs();
		}

		return getDataTable(list);
	}

	/**
	 * 查询数据表字段列表
	 * jm250421 前端并没有使用这个api
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:list')")
	@GetMapping(value = "/column/{tableId}")
	public TableDataInfo columnList(Long tableId) {

		Boolean dsChanged = changeDs(datasource);
		TableDataInfo dataInfo = new TableDataInfo();
		List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
		dataInfo.setRows(list);
		dataInfo.setTotal(list.size());

		if (dsChanged)
			resetDs();
		return dataInfo;
	}

	/**
	 * 导入表结构（保存）
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:import')")
	@Log(title = "代码生成", businessType = BusinessType.IMPORT)
	@PostMapping("/importTable")
	public AjaxResult importTableSave(String dsname, String tables) {

		Boolean dsChanged = changeDs(dsname);
		try {			
			String[] tableNames = Convert.toStrArray(tables);
			// 查询表信息
			List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
			genTableService.importGenTable(tableList, SecurityUtils.getUsername());
		}catch (Exception e) {
			// TODO: handle exception
			if (dsChanged)
				resetDs();
			return error();
		} finally {			
			if (dsChanged)
				resetDs();
		} 
		
		return success();
	}

	/**
	 * 创建表结构（保存）
	 */
	@PreAuthorize("@ss.hasRole('admin')")
	@Log(title = "创建表", businessType = BusinessType.OTHER)
	@PostMapping("/createTable")
	public AjaxResult createTableSave(String sql, String dsname) {

		Boolean dsChanged = changeDs(dsname);
		try {
			SqlUtil.filterKeyword(sql);
			List<SQLStatement> sqlStatements = SQLUtils.parseStatements(sql, DbType.mysql);
			List<String> tableNames = new ArrayList<>();
			for (SQLStatement sqlStatement : sqlStatements) {
				if (sqlStatement instanceof MySqlCreateTableStatement) {
					MySqlCreateTableStatement createTableStatement = (MySqlCreateTableStatement) sqlStatement;
					if (genTableService.createTable(createTableStatement.toString())) {
						String tableName = createTableStatement.getTableName().replaceAll("`", "");
						tableNames.add(tableName);
					}
				}
			}
			List<GenTable> tableList = genTableService
					.selectDbTableListByNames(tableNames.toArray(new String[tableNames.size()]));
			String operName = SecurityUtils.getUsername();
			genTableService.importGenTable(tableList, operName);

			if (dsChanged)
				resetDs();
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);

			if (dsChanged)
				resetDs();
			return AjaxResult.error("创建表结构异常");
		}
	}

	/**
	 * 修改保存代码生成业务
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:edit')")
	@Log(title = "代码生成", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {

		Map<String, Object> queryParams = genTable.getParams();

		Boolean dsChanged = changeDs(queryParams);
		genTableService.validateEdit(genTable);
		genTableService.updateGenTable(genTable);

		if (dsChanged)
			resetDs();
		return success();
	}

	/**
	 * 删除代码生成
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:remove')")
	@Log(title = "代码生成", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tableIds}")
	public AjaxResult remove(@PathVariable Long[] tableIds, @RequestParam String dsname) {

		Boolean dsChanged = changeDs(dsname);
		genTableService.deleteGenTableByIds(tableIds);

		if (dsChanged)
			resetDs();
		return success();
	}

	/**
	 * 预览代码
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:preview')")
	@GetMapping("/preview/{tableId}")
	public AjaxResult preview(@PathVariable("tableId") Long tableId, @RequestParam String dsname) {

		Boolean dsChanged = changeDs(dsname);
		Map<String, String> dataMap = genTableService.previewCode(tableId);

		if (dsChanged)
			resetDs();
		return success(dataMap);
	}

	/**
	 * 生成代码（下载方式）
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:code')")
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/download/{tableName}")
	public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {

		Boolean dsChanged = changeDs(datasource);
		byte[] data = genTableService.downloadCode(tableName);
		genCode(response, data);

		if (dsChanged)
			resetDs();
	}

	/**
	 * 生成代码（自定义路径）
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:code')")
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/genCode/{tableName}")
	public AjaxResult genCode(@PathVariable("tableName") String tableName, @RequestParam String dsname) {
		if (!GenConfig.isAllowOverwrite()) {
			return AjaxResult.error("【系统预设】不允许生成文件覆盖到本地");
		}

		Boolean dsChanged = changeDs(dsname);
		genTableService.generatorCode(tableName);

		if (dsChanged)
			resetDs();
		return success();
	}

	/**
	 * 同步数据库
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:edit')")
	@Log(title = "代码生成", businessType = BusinessType.UPDATE)
	@GetMapping("/synchDb/{tableName}")
	public AjaxResult synchDb(@PathVariable("tableName") String tableName ,@RequestParam String dsname ) {

		Boolean dsChanged = changeDs(dsname);
		genTableService.synchDb(tableName);

		if (dsChanged)
			resetDs();
		return success();
	}

	/**
	 * 批量生成代码
	 */
	@PreAuthorize("@ss.hasPermi('tool:gen:code')")
	@Log(title = "代码生成", businessType = BusinessType.GENCODE)
	@GetMapping("/batchGenCode")
	public void batchGenCode(HttpServletResponse response, @RequestParam  String tables, @RequestParam String dsname) throws IOException {

		Boolean dsChanged = changeDs(dsname);
		String[] tableNames = Convert.toStrArray(tables);
		byte[] data = genTableService.downloadCode(tableNames);
		genCode(response, data);

		if (dsChanged)
			resetDs();
	}

	/**
	 * 生成zip文件
	 */
	private void genCode(HttpServletResponse response, byte[] data) throws IOException {

		Boolean dsChanged = changeDs(datasource);
		response.reset();
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		// 设置允许跨域
		response.addHeader("Access-Control-Allow-Origin", "*");

		IOUtils.write(data, response.getOutputStream());

		if (dsChanged)
			resetDs();
	}

	private Boolean changeDs(String datasource) {
		DynamicDataSourceContextHolder.push(datasource); // jm 手动切换开始
		return true;
	}

	private Boolean changeDs(Map<String, Object> params) {
		Object dsName = params.get("dsName");
		if (dsName instanceof String) {
			DynamicDataSourceContextHolder.push((String) dsName); // jm 手动切换开始
			return true;
		} else
			return false;
	}

	private void resetDs() {
		DynamicDataSourceContextHolder.clear();// jm 手动切换结束
	}
}